﻿using System;
using System.IO;
using System.Text;
using href.Utils;

namespace Poet.Modules
{
    public static class EncodingModule
    {
        public static Encoding DetectBestEncoding(string fileName, int offset = 0, int length = 500000)
        {
            var encodings = DetectInputEncodings(fileName, offset, length);
            return encodings.Length > 0 ? encodings[0] : null;
        }

        public static Encoding DetectBestEncoding(Stream inputStream, int offset = 0, int length = 500000)
        {
            var encodings = DetectInputEncodings(inputStream, offset, length);
            return encodings.Length > 0 ? encodings[0] : null;
        }

        public static Encoding[] DetectInputEncodings(string fileName, int offset = 0, int length = 500000, int maxSuggestedEncodings = 1)
        {
            var fileLength = (int) new FileInfo(fileName).Length;
            if (length > fileLength) length = fileLength;
            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                return DetectInputEncodings(stream, offset, length, maxSuggestedEncodings);
        }

        public static Encoding[] DetectInputEncodings(Stream inputStream, int offset = 0, int length = 500000, int maxSuggestedEncodings = 1)
        {
            var buffer = new byte[length];
            var bytesCount = inputStream.Read(buffer, offset, length);
            if (bytesCount < buffer.Length)
            {
                var tmp = new byte[bytesCount];
                Array.Copy(buffer, tmp, bytesCount);
                buffer = tmp;
            }

            return EncodingTools.DetectInputCodepages(buffer, maxSuggestedEncodings);
        }
    }
}
